//
//  HistoryViewController.m
//  Riese
//
//  Created by air on 2019/10/26.
//  Copyright © 2019 wangjinyu. All rights reserved.
//

#import "HistoryViewController.h"
#import "HistoryCell.h"
#import <MMAlertView.h>

#import "DetailViewController.h"

@interface HistoryViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *mainTable;
@property (nonatomic, strong) NSMutableArray * dataArray;
@property (nonatomic, strong) NSMutableArray *idArray;

@property (nonatomic, strong) FMDatabase *db;

@end

@implementation HistoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = NSLocalizedString(@"Historical cases", nil);
    self.view.backgroundColor = kColor(243, 243, 243);
    
    self.dataArray = [NSMutableArray arrayWithCapacity:0];
    self.idArray = [NSMutableArray arrayWithCapacity:0];
    
    [self makeUI];
    [self getData];
}

- (void)makeUI {
    self.mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.mainTable.backgroundColor = [UIColor clearColor];
    self.mainTable.delegate = self;
    self.mainTable.dataSource = self;
    self.mainTable.showsVerticalScrollIndicator = NO;
    self.mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTable.estimatedRowHeight = 0;
    self.mainTable.estimatedSectionHeaderHeight = 0;
    self.mainTable.estimatedSectionFooterHeight = 0;
    [self.view addSubview:self.mainTable];
    
    [self makeHeader];
}

#pragma mark - getData
- (void)getData {
    // 创建数据库对象  如果没有选择用户
    NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString * path = [docsdir stringByAppendingPathComponent:@"DeviceData.sqlite"];//将需要创建的串拼接到后面
    self.db = [FMDatabase databaseWithPath:path];
    // 建表
    [self createDataDevice];
}

#pragma mark - dataDevice FMDB
// 创建表
- (void)createDataDevice{

   if ([self.db open]) {
       //AUTOINCREMENT 自增
       if (![self isExistTable:@"DeviceData"]) {
           BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS DeviceData(ID INTEGER PRIMARY KEY AUTOINCREMENT,'uid' 'text', 'json' 'text');"];
           if (result) {
               //[ProgressHUD showSuccess:@"创建表成功"];
               [self selectData];
               
           }else{
               [YJProgressHUD showMessage:@"创建表失败" inView:self.view];
           }
           [self.db close];
       }
       else {
           [self selectData];
           [self.db close];
       }
   }else{
       [YJProgressHUD showMessage:@"数据库打开失败" inView:self.view];
   }
}

// 查询数据
- (void)selectData {
    [self.dataArray removeAllObjects];
    [self.idArray removeAllObjects];
    NSString *query = [NSString stringWithFormat:@"select * from DeviceData where uid='%@'", defaults(@"id")];
    FMResultSet *rs = [self.db executeQuery:query];
    // 遍历结果集
    while ([rs next]) {
        NSDictionary *dic = [self dictionaryWithJsonString:[rs stringForColumn:@"json"]];
        [self.dataArray addObject:dic];
        [self.idArray addObject:[rs stringForColumn:@"ID"]];
    }
    
    [self.mainTable reloadData];
}

/**
 判断一张表是否已经存在
 @param tablename 表名
 */
- (BOOL)isExistTable:(NSString *)tablename{
    NSString *sql = [NSString stringWithFormat:@"SELECT COUNT(*) FROM sqlite_master where type= 'table' and name= '%@';",tablename];
    FMResultSet *rs = [self.db executeQuery:sql];
//    BOOL result = [db executeQuery:sql];
    while ([rs next]) {
        NSInteger count = [rs intForColumnIndex:0];
        if (count == 0) {
            return NO;
        }else {
            return YES;
        }
    }
    return NO;
}

-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
    NSLog(@"json解析失败：%@",err);
    return nil;
    }
    return dic;
}

-(NSString *)convertToJsonData:(NSDictionary *)dict {

    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    return mutStr;
}

#pragma mark - makeUI
- (void)makeHeader {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 140)];
    header.backgroundColor = [UIColor clearColor];
    self.mainTable.tableHeaderView = header;
    
    UIButton *btn_ImgV = [UIButton buttonWithType:UIButtonTypeCustom];
    [header addSubview:btn_ImgV];
    
    btn_ImgV.sd_layout.leftSpaceToView(header, SCREEN_WIDTH / 2 - 57).topSpaceToView(header, 10).widthIs(114).heightIs(114);
    [btn_ImgV setBackgroundImage:[UIImage imageNamed:@"addUser_icon"] forState:UIControlStateNormal];
    
    UIImageView *avatar = [[UIImageView alloc] initWithFrame:CGRectMake(13, 1, 88, 88)];
    avatar.layer.cornerRadius = 44;
    avatar.clipsToBounds = YES;
    avatar.image = self.avatarImg;
    [btn_ImgV addSubview:avatar];
    
    UILabel * lab_nickname = [[UILabel alloc] init];
    [header addSubview:lab_nickname];
    lab_nickname.textColor = UIColorFromHex(0x666666);
    lab_nickname.textAlignment = NSTextAlignmentCenter;
    lab_nickname.sd_layout.leftSpaceToView(header, 0).topSpaceToView(header, 110).rightSpaceToView(header, 0).heightIs(25);
    lab_nickname.text = self.nickname;
}

#pragma mark - tableView delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellIdentifier = @"HistoryCell";
    HistoryCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[NSBundle mainBundle] loadNibNamed:cellIdentifier owner:self options:nil].firstObject;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = self.dataArray[indexPath.row];
    
    cell.longPressGesture.view.tag = indexPath.row;
    [cell.longPressGesture addTarget:self action:@selector(cellLongPress:)];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 140;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *vc = [DetailViewController new];
    vc.dataDic = self.dataArray[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma - mark cell长按手势 长按删除
-(void)cellLongPress:(UILongPressGestureRecognizer *)longRecognizer{
    if (longRecognizer.state==UIGestureRecognizerStateBegan) {
        //成为第一响应者，需重写该方法
        [self becomeFirstResponder];
        //MMAlertView
        NSArray *items = @[MMItemMake(NSLocalizedString(@"cancel", nil), MMItemTypeNormal, nil), MMItemMake(NSLocalizedString(@"sure", nil), MMItemTypeNormal, ^(NSInteger index) {
            [self createDeleteData:longRecognizer.view.tag];
        })];
        
        [[[MMAlertView alloc] initWithTitle:@"" detail:[NSString stringWithFormat:@"\n%@", NSLocalizedString(@"Are you sure to delete?", nil)] items:items] show];
    }
}

#pragma mark - 删除数据(长按删除) FMDB
// 创建表
- (void)createDeleteData:(NSInteger)index {

   if ([self.db open]) {
       //AUTOINCREMENT 自增
       if (![self isExistTable:@"DeviceData"]) {
           BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS DeviceData(ID INTEGER PRIMARY KEY AUTOINCREMENT,'uid' 'text', 'json' 'text');"];
           if (result) {
               //[ProgressHUD showSuccess:@"创建表成功"];
               [self deleteData:index];
               
           }else{
               [YJProgressHUD showMessage:@"创建表失败" inView:self.view];
           }
           [self.db close];
       }
       else {
           [self deleteData:index];
           [self.db close];
           [self getData];
       }
   }else{
       [YJProgressHUD showMessage:@"数据库打开失败" inView:self.view];
   }
}

// 删除数据
- (void)deleteData:(NSInteger)index {
    NSString *query = [NSString stringWithFormat:@"delete from DeviceData where %@ = %@", @"ID", self.idArray[index]];
    BOOL res = [self.db executeUpdate:query];
    
    if (res) {
        [YJProgressHUD showMessage:NSLocalizedString(@"Delete successfully", nil) inView:self.view];
    }
    else {
        [YJProgressHUD showMessage:NSLocalizedString(@"Delete failed", nil) inView:self.view];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
